<template>
  <div class="p-2">
    <!-- 设备管理 - 设备列表 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
        <!-- <el-form-item label="设备ID" prop="id">
          <el-input v-model="queryParams.id" placeholder="请输入设备ID" clearable style="width: 200px" />
        </el-form-item> -->
        <el-form-item label="设备编号" prop="deviceCode">
          <el-input v-model="queryParams.deviceCode" placeholder="请输入设备编号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="设备ICCID" prop="iccid">
          <el-input v-model="queryParams.iccid" placeholder="请输入设备ICCID" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="产品ID" prop="productId">
          <el-input v-model="queryParams.productId" placeholder="请输入产品ID" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增设备</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Refresh" @click="handleRefreshStatus">刷新状态</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备ID" prop="id" width="120" show-overflow-tooltip />
        <el-table-column label="设备编号" prop="deviceCode" width="150" show-overflow-tooltip />
        <el-table-column label="设备ICCID" prop="iccid" width="180" show-overflow-tooltip />
        <el-table-column label="产品ID" prop="productId" width="120" show-overflow-tooltip />
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改设备对话框 -->
    <DeviceFormDialog
      v-model:visible="dialog.visible"
      :title="dialog.title"
      :form-data="dialog.data"
      @submit="submitForm"
      @cancel="cancel"
    />

  </div>
</template>

<script setup name="DeviceList" lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download, Upload } from '@element-plus/icons-vue'
import type { DeviceInfo, DeviceQueryParams } from '@/api/IOT/deviceManage/types'

import DeviceFormDialog from './components/DeviceFormDialog.vue'


// 响应式数据
const loading = ref(false)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const deviceList = ref<DeviceInfo[]>([])

// 查询参数
const queryParams = reactive<DeviceQueryParams>({
  pageNum: 1,
  pageSize: 10,
  deviceCode: '',
  productId: '',
  id: '',
  iccid: '',
  status: undefined
})

// 对话框状态
const dialog = reactive({
  visible: false,
  title: '',
  data: null
})

// 获取状态标签样式
const getStatusTag = (status: number) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'danger'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 1: return '启用'
    case 0: return '停用'
    default: return '未知'
  }
}

// 本地虚拟延迟（随机不超过1.5s）
const delayRandom = (min = 300, max = 1500) => new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * (max - min + 1)) + min))

// 本地设备数据源
const allDevices = ref<DeviceInfo[]>([])

// 初始化设备数据
const initDevices = () => {
  if (allDevices.value.length) return
  const products = ['P-1001','P-1002','P-1003','P-1004']
  const list: DeviceInfo[] = []
  for (let i = 1; i <= 60; i++) {
    list.push({
      id: `${100000 + i}`,
      deviceCode: `DEV-${String(i).padStart(4, '0')}`,
      iccid: `89860${String(1000000000 + i).padStart(10, '0')}`,
      productId: products[i % products.length],
      status: i % 3 === 0 ? 0 : 1,
      remark: i % 5 === 0 ? '需巡检' : ''
    } as any)
  }
  allDevices.value = list
}

initDevices()

// 获取设备列表（本地虚拟请求）
const getList = async () => {
  loading.value = true
  try {
    await delayRandom()
    let filtered = [...allDevices.value]
    if (queryParams.deviceCode) filtered = filtered.filter(d => d.deviceCode.includes(queryParams.deviceCode))
    if (queryParams.iccid) filtered = filtered.filter(d => d.iccid.includes(queryParams.iccid))
    if (queryParams.productId) filtered = filtered.filter(d => d.productId === queryParams.productId)
    if (queryParams.status !== undefined && queryParams.status !== null && queryParams.status !== '') filtered = filtered.filter(d => d.status === queryParams.status)
    const start = (queryParams.pageNum - 1) * queryParams.pageSize
    const end = start + queryParams.pageSize
    deviceList.value = filtered.slice(start, end)
    total.value = filtered.length
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
  } finally {
    loading.value = false
  }
}

// 删除按钮操作（本地虚拟请求）
const handleDelete = (row?: any) => {
  const deviceIds: string[] = row?.id ? [row.id] : ids.value as any
  ElMessageBox.confirm('是否确认删除设备ID为"' + deviceIds.join(',') + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      await delayRandom()
      const idSet = new Set(deviceIds)
      allDevices.value = allDevices.value.filter(d => !idSet.has(d.id))
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 导出按钮操作（本地虚拟请求）
const handleExport = async () => {
  try {
    await delayRandom()
    const data = deviceList.value
    const header = ['设备ID','设备编号','设备ICCID','产品ID','状态','备注']
    const rows = data.map(d => [d.id, d.deviceCode, d.iccid, d.productId, d.status === 1 ? '启用' : '停用', d.remark || ''])
    const csv = [header.join(','), ...rows.map(r => r.map(v => `"${String(v).replace(/"/g, '""')}"`).join(','))].join('\n')
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `设备列表_${Date.now()}.csv`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 提交表单（本地新增/修改）
const submitForm = async (formData: any) => {
  try {
    loading.value = true
    await delayRandom()
    if (dialog.title === '修改设备') {
      const idx = allDevices.value.findIndex(d => d.id === formData.id)
      if (idx !== -1) {
        allDevices.value[idx] = { ...allDevices.value[idx], ...formData }
      }
      ElMessage.success('修改成功')
    } else {
      const newId = String(Math.max(0, ...allDevices.value.map(d => parseInt(d.id || '0'))) + 1)
      allDevices.value.unshift({ ...formData, id: newId })
      ElMessage.success('添加成功')
    }
    dialog.visible = false
    getList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(dialog.title === '修改设备' ? '修改失败' : '添加失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.id = ''
  queryParams.deviceCode = ''
  queryParams.iccid = ''
  queryParams.productId = ''
  queryParams.status = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '添加设备'
}

// 修改按钮操作
const handleUpdate = (row?: any) => {
  const deviceId = row?.id || ids.value[0]
  // 模拟获取详情
  const device = deviceList.value.find(item => item.id === deviceId)
  if (device) {
    dialog.data = device
  }
  dialog.visible = true
  dialog.title = '修改设备'
}





// 刷新状态
const handleRefreshStatus = () => {
  ElMessage.success('设备状态刷新成功')
  getList()
}

// 取消操作
const cancel = () => {
  dialog.visible = false
}

// 组件挂载
onMounted(() => {
  getList()
})
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>